package com.chb.rpc;

import com.chb.entity.RpcRequest;
import com.chb.utils.IoUtils;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @description:
 * @author: CHB
 * @create: 2022-03-14 10:21
 **/
public class RpcNetTransport {

    private String host;
    private Integer port;

    public RpcNetTransport(String host, Integer port){
        this.host = host;
        this.port = port;
    }

    /**
     * 向指定ip发送请求并接受返回结果
     * @param rpcRequest
     * @return
     */
    public Object remoteCall(RpcRequest rpcRequest) {
        Socket socket = null;
        Object result = null;
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        try {
            socket = new Socket(host,port);
            // 向指定主机端口发送请求
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(rpcRequest);
            outputStream.flush();

            // 接受返回的参数
            inputStream = new ObjectInputStream(socket.getInputStream());
            result = inputStream.readObject();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            IoUtils.close(outputStream,inputStream,socket);
        }
        return result;
    }
}
